//导入路由函数
import {
  createRouter,
  createWebHistory,
  type RouteRecordRaw,
} from "vue-router";
import { useToken } from "@/stores/token"; //导入token状态文件

//定义路由规则
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: () => import("@/views/Layout/index.vue"),
    children: [
      {
        path: "",
        alias: ["/index"],
        component: () => import("@/views/Index/index.vue"),
        meta: {
          title: "首页",
        },
      },
      {
        path: "/category",
        component: () => import("@/views/Category/index.vue"),
        meta: {
          title: "分类管理",
        },
      },
      {
        path: "/goods",
        component: () => import("@/views/Goods/index.vue"),
        meta: {
          title: "商品管理",
        },
      },
      {
        path: "/user",
        component: () => import("@/views/User/index.vue"),
        meta: {
          title: "用户设置",
        },
      },
      {
        path: "/manager",
        component: () => import("@/views/Manager/index.vue"),
        meta: {
          title: "管理员设置",
        },
      },
      {
        path: "/person",
        component: () => import("@/views/Person/index.vue"),
        meta: {
          title: "个人中心",
        },
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/Login/index.vue"),
    meta: {
      title: "登录",
    },
  },
];

//创建路由
const router = createRouter({
  history: createWebHistory(),
  routes,
});

//声明全局前置守卫：管理员登录后，才能访问后台管理页面
router.beforeEach((to, _from, next) => {
  document.title = to.meta.title + " - 后台管理系统";
  //执行方法获得tokenStore对象
  const tokenStore = useToken();

  if (to.path == "/login") {
    //访问后台登录页面：放行
    next();
  } else {
    //管理员是否登录
    if (tokenStore.token) {
      //管理员登录后，访问任意页面：放行
      next();
    } else {
      //管理员未登录，只能访问"/login"登录页面
      next("/login");
    }
  }
});

//导出路由
export default router;
